package server;

import server.components.Context;
import server.components.Host;
import server.components.Mapper;
import server.components.Wrapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.List;

/**
 * 多线程改造封装
 */
public class RequestProcessor extends Thread {

    private Socket socket;

    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());

            String url = request.getUrl();
            // 处理地址  取出访问项目  具体servlet地址信息
            String contextName = url.split("/")[1];
            String servletName = url.split("/")[2];

            List<Host> hosts = mapper.getHosts();
            //循环查找请求所传得方法与类信息
            for (Host host : hosts) {
                List<Context> contexts = host.getContexts();
                for (Context context : contexts) {
                    if (context.getPath().equalsIgnoreCase(contextName)) {
                        List<Wrapper> wrappers = context.getWrappers();
                        for (Wrapper wrapper : wrappers) {
                            if (wrapper.getUrl().equalsIgnoreCase("/" + servletName)) {
                                wrapper.getServlet().service(request,response);
                            }
                        }
                    }
                }
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
